var util = require('util');
var EventEmitter = require('events').EventEmitter;
var request = require('request');
var debug = true;

function ScheduleTask() {
	// 任务保存的数据
	this.taskData = [];
}
util.inherits(ScheduleTask, EventEmitter);

/**
 * 启动任务的入口
 */
function startTask(aTask) {
	if (debug) console.log('>>>>>>>>>>> start');
	aTask.emit('get_all_devices', aTask);
}

/**
 * 错误日志输出
 */
function taskError(aTask, error) {
	console.log(error);
}

/**
 * 获取所有设备，保存到aTask.taskData[index].device中，然后触发下一个事件
 */
function get_all_devices(aTask) {
	if (debug) console.log('>>>>>>>>>>> get_all_devices');
	var url = 'http://115.28.0.60/mdm/api/v1/devices/?pageSize=100000&available=true'
	request(url, function(error, res, data) {
		if (error) {
			aTask.emit('error', aTask, 'get devices list fail' + error.toString());
			return;
		}
		if (!res.statusCode == 200) {
			aTask.emit('error', aTask, 'get_all_device res.statusCode != 200');
			return;
		}

		data = string2Json(data);
		var preserved = string2Json(data.preserved);
		var list = preserved.list;

		// filter
		list = list.filter(function(device) {
			return (device.deviceId && device.deviceId !== 'null') && device.online;
			// && device.available;
		})

		list.forEach(function(device) {
			aTask.taskData.push({
				device: device
			});
			console.log('@device ' + device.deviceDetail.deviceName + ':' + device.name);
		});

		// emit event;
		if (debug) console.log('>>>>>>>>>>> get_all_devices_done');
		aTask.emit('generate_task', aTask);
	});
}

/**
 * 对aTask.taskData中的每个device,生成任务,将任务的返回保存到
 * aTask.taskData[index].genTaskResp,然后触发下一个事件
 */
function generate_task(aTask) {
	if (debug) console.log('>>>>>>>>>>> generate_task');
	if (!aTask.taskData) {
		aTask.emit('error', aTask, 'null deviceList');
		return;
	}
	if (!Array.isArray(aTask.taskData)) {
		aTask.emit('error', aTask, 'taskData should be Array');
		return;
	}
	if (aTask.taskData.length === 0) {
		aTask.emit('error', aTask, 'taskData length = 0,which means no device exist');
		return;
	}

	aTask.taskData.forEach(function(itemData, index) {
		var device = itemData.device;

		// prepare request form data
		var param = {
			url: '',
			formData: ''
		};
		if (device.deviceDetail.osName === 'android') {
			param.url = 'http://bsl.foreveross.com/mdm/api/v1/commands/18';
			var preserved = {
				"type": "mdm",
				"content": {
					"get_installed_applist": ""
				}
			}
			param.formData = {
				platform: device.deviceDetail.osName,
				deviceId: device.deviceId,
				cmdName: "获取设备应用列表",
				preserved: JSON.stringify(preserved)
			};
		} else if (device.deviceDetail.osName === 'ios') {
			param.url = 'http://bsl.foreveross.com/mdm/api/v1/commands/8';
			param.formData = {
				platform: device.deviceDetail.osName,
				deviceId: device.deviceId,
				cmdName: "获取设备应用列表",
				apnsToken: device.deviceDetail.pushToken,
				preserved: ''
			};
		} else {
			param = null;
			aTask.emit('error', aTask, 'device is not android or ios');
			return;
		}

		// send request
		request.post(param, function(err, res, body) {
			if (err) {
				console(err);
				callback('get install list response err');
			} else {
				body = string2Json(body);
				itemData.genTaskResp = body;
				aTask.emit('get_app_list', aTask, index);
			}
		});
	});
}

var wait_response_time = 5 * 1000;
/**
 * 对aTask.taskData中的每个device,获取app列表,
 * 存放到 aTask.taskData[index].appList中,然后触发下一个事件
 */
function get_app_list(aTask, index) {
	var device = aTask.taskData[index].device;
	var genTaskResp = aTask.taskData[index].genTaskResp;
	if (debug) console.log('>>>>>>>>>>> get_app_list, ' + device.deviceDetail.deviceName + ':' + device.name);

	var url;
	var cmdUuid = genTaskResp.preserved;
	url = 'http://bsl.foreveross.com/mdm/api/v1/tasks/?cmdUuid=' + cmdUuid;
	console.log(url);
	// if (device.deviceDetail.osName === 'android') {
	// 	var cmdUuid = genTaskResp.preserved;
	// 	url = 'http://bsl.foreveross.com/mdm/api/v1/tasks/?cmdUuid=' + cmdUuid;
	// } else if (device.deviceDetail.osName === 'ios') {
	// 	console.log(genTaskResp);
	// 	var cmdUuid = genTaskResp.preserved;
	// 	url = 'http://bsl.foreveross.com/mdm/api/v1/tasks/?cmdUuid=' + cmdUuid;
	// } else {
	// 	aTask.emit('error', aTask, 'device is not android or ios');
	// 	return;
	// }

	setTimeout(function() {
		// do request
		request.get(url, function(error, res, data) {
			if (error) {
				aTask.emit('error', aTask, 'get app list fail :' + error.toString());
				return;
			}

			try {
				data = string2Json(data);
				var preserved = string2Json(data.preserved);
				var list = string2Json(preserved.list);
				var list0 = string2Json(list[0]);
				var status = list0.status;
				if (status === 'ok') {
					var rlt = string2Json(list0.rlt);
					var appList;
					if (device.deviceDetail.osName === 'android') {
						appList = rlt.list;
					} else {
						appList = rlt.InstalledApplicationList;
						appList = string2Json(appList);
					}


					aTask.taskData[index].appList = appList;
					aTask.emit('get_app_list_done', aTask, index);
				} else {
					aTask.emit('error', aTask, 'get_app_list:status not ok');
				}
			} catch (error) {
				var errorInfo = '';
				errorInfo += '@device ' + device.deviceDetail.deviceName + ':' + device.name;
				errorInfo += ' parse data fail, device maybe offline';
				aTask.emit('error', aTask, errorInfo);
			}
		});
	}, wait_response_time);
}

var count = 0;

function get_app_list_done(aTask, index) {
	var device = aTask.taskData[index].device;
	var genTaskResp = aTask.taskData[index].genTaskResp;
	var appList = aTask.taskData[index].appList;

	console.log('@device ' + device.deviceDetail.deviceName + ':' + device.name);
	var allName = '';
	appList.forEach(function(item, index) {
		var name = item.Name ? item.Name : item.appName;
		allName += '\t' + name + '\t';
		if ((index + 1) % 4 == 0) {
			allName += '\n'
		}
	})
	console.log(allName);
	count++;
	// aTask.emit('finish', aTask, index);
	if (count === aTask.taskData.length) {
		aTask.emit('finish_all', aTask);
	}
}

// function finish(aTask, index) {
// 	aTask.taskData[index] = null;
// }


function finish_all(aTask) {
	aTask.taskData = null;
	aTask = null;
	console.log('==============task finish==========');
}


function newTask() {
	var aTask = new ScheduleTask();
	// aTask.taskData = [];
	aTask.on('error', taskError);
	aTask.on('get_all_devices', get_all_devices);
	aTask.on('generate_task', generate_task);
	aTask.on('get_app_list', get_app_list);
	aTask.on('get_app_list_done', get_app_list_done);
	// aTask.on('finish', finish);
	aTask.on('finish_all', finish_all);
	return aTask;
}

/**
 * utils function
 *
 * if string then return JSON.parse(str)
 * else return the input
 */
function string2Json(str) {
	var result = (typeof str) === 'string' ? JSON.parse(str) : str;
	return result;
}

module.exports = {
	newTask: newTask,
	start: startTask
};